<template>
  <avue-crud
    ref="avueCrud"
    :option="optionList"
    :data="dataList"
    @cell-click="handleRowClick"
    :class="{ maxHeight: !dataList.length }"
  >
    <template #menu-left="{}">
      <slot name="selfDefined"></slot>
    </template>
    <slot></slot>
    <template #stage-header="{ column }">
      <div class="request">{{ (column || {}).label }}</div>
    </template>
    <template #conditions-header="{ column }">
      <div class="request">{{ (column || {}).label }}</div>
    </template>
    <template #planAccepDate-header="{ column }">
      <div class="request">{{ (column || {}).label }}</div>
    </template>
    <template #planReturnSum-header="{ column }">
      <div class="request">{{ (column || {}).label }}</div>
    </template>
    <template #fileName="{ row, index }">
      <el-upload
        v-model:file-list="fileList[row.pcId]"
        class="upload-demo"
        action="#"
        :data-id="row.id"
        :http-request="changeFile"
        accept=".rar, .zip, .doc, .docx, .pdf"
        :show-file-list="false"
      >
        <el-button
          type="default"
          style="font-size: 12px; width: 80px"
          @click="asd(index)"
          >上传文件</el-button
        >
      </el-upload>
      <div
        class="text-14px mt-10px"
        style="width: 100%"
        v-if="row.origFileName"
      >
        <a :href="row.fileUrl" target="_blank">{{ row.origFileName }}</a>
        <el-button
          text
          plain
          type="primary"
          @click="delFileFn(index)"
          class="ml-10px"
          >删除</el-button
        >
      </div>
    </template>
    <template #menu="{ row, index }">
      <el-button
        text
        type="primary"
        :icon="row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'"
        @click="rowCell(row, index)"
        v-if="actionBarForSave || !row.$cellEdit"
        >{{ row.$cellEdit ? '保存' : '编辑' }}</el-button
      >
      <el-button
        text
        icon="el-icon-cancel"
        type="primary"
        @click="rowCancel(row, index)"
        >删除</el-button
      >
    </template>
  </avue-crud>
  <div class="statistics" v-if="statistics.length" :style="{ width }">
    <div class="statisticsBox">
      <div
        class="pr-10px"
        v-for="item in statistics"
        :key="item.label + item.key"
      >
        {{ item.label }}:<span class="ml-5px">{{
          (item.unitPlace === 'before' ? item.unit : '') +
          total(item) +
          (item.unitPlace === 'after' ? item.unit : '')
        }}</span>
      </div>
    </div>
  </div>
  <slot name="footerForm"></slot>
</template>

<script setup name="EditTable">
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import {
  reactive,
  toRefs,
  computed,
  watchEffect,
  getCurrentInstance,
  watch
} from 'vue'

const { proxy } = getCurrentInstance()
const data = reactive({
  dataList: [],
  optionList: []
})
const { dataList, optionList } = toRefs(data)
const fileList = ref({})
let watchDataList = []
const emit = defineEmits(['rowClick', 'rowSave', 'rowDelete'])
const props = defineProps({
  // 统计展示字段
  statistics: {
    type: Array,
    default: () => []
  },
  // 配置数据
  option: {
    type: Object,
    default: () => {},
    required: true
  },
  // 展示数据
  data: {
    type: Object,
    default: () => {},
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  // 新增时展示保存
  actionBarForSave: {
    type: Boolean,
    default: true
  }
})
const uploadIndex = ref(-1)

function asd(index) {
  uploadIndex.value = index
}

const column = computed(() => {
  return optionList.value.column.map(item => {
    return item.prop
  })
})

watchEffect(
  () => {
    dataList.value = props.data
    optionList.value = props.option
  },
  {
    flush: 'post'
  }
)

// 统计数据计算
const total = computed(() => item => {
  let result = 0
  switch (item.type) {
    case 'sum':
      dataList.value.forEach(v => {
        if (v[item.key]) {
          result += Number(v[item.key])
        }
      })
      break
    case 'length':
      result = dataList.value.length
      break
    case 'ave':
      let length = dataList.value.length
      let sum = 0
      dataList.value.forEach(v => {
        if (v[item.key]) {
          sum += Number(v[item.key])
        }
      })
      result = sum / length
  }
  return result
})
// 文件上传
async function changeFile(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      let index = parseInt(uploadIndex.value)
      dataList.value[index].fileName = res.data.fileName
      dataList.value[index].origFileName = res.data.origFileName
      dataList.value[index].fileUrl = res.data.url
      emit('rowSave', dataList.value[index], index)
    }
  } catch (error) {
    console.log(error)
    // proxy.$modal.msgError(error)
  }
}
// 删除文件
function delFileFn(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = dataList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        dataList.value[index].fileName = ''
        dataList.value[index].origFileName = ''
        dataList.value[index].fileUrl = ''
        emit('rowSave', dataList.value[index], index)
      }
    })
  } catch (error) {
    console.log(error)
    // proxy.$modal.msgError(error)
  }
}
// 单元格点击事件
function handleRowClick(row, column, cell, event) {
  emit('rowClick', row, column, cell, event)
}

// 行编辑|保存
function rowCell(row, index) {
  if (row.$cellEdit) {
    // 检验是否有除备注外未填内容 -- todo  添加其他可不填字段
    const arr = column.value.filter(item => {
      if (item !== 'remark' && item !== 'planAccepRatio' && !row[item]) {
        return item
      }
    })
    if (arr.length) {
      proxy.$modal.msgWarning('表格存在未填内容')
      return
    }
    row.$cellEdit = false

    emit('rowSave', row, index)
  } else {
    const oldVal = { ...toRaw(row) }
    const arr = dataList.value.filter(v => v.$cellEdit)
    if (arr.length === 1) {
      proxy.$modal.msgWarning('存在未保存内容，请先保存')
      return
    }
    row.$cellEdit = true
    watchDataList = oldVal
  }
}

// 取消/删除
function rowCancel(row, index) {
  proxy.$modal
    .confirm('是否确认删除?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      dataList.value.splice(index, 1)
      emit('rowDelete', row, index)
    })
}

// 返回表格数据
function returnData() {
  return dataList.value
}
// 暴露方法
defineExpose({ returnData })
</script>

<style scoped lang="scss">
.statistics {
  @apply px-20px mb-20px;
  margin: 0 auto 20px;
  .statisticsBox {
    @apply flex justify-end  h-50px items-center px-20px font-bold;
    font-size: 12px;
    background-color: rgb(248, 248, 249);
    border: 1px solid #ebeef5;
    span {
      @apply font-medium;
    }
  }
}
// .maxHeight :deep .el-scrollbar__view {
//   height: 180px !important;
//   overflow: hidden;
// }
.request::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}
:deep .el-empty__description {
  margin: none !important;
}
:deep .el-empty__image {
  display: none;
}
:deep .avue-crud__empty {
  padding: 0;
}
:deep .el-empty {
  padding: 0;
}
</style>
